import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import { config } from '../../shared/smartadmin.config';
import { DatePickerModule } from '../../shared/date-picker/date-picker.module';

declare var $: any;
@Component({
	selector: 'sa-docking-manage',
	templateUrl: './docking-manage.component.html',
	styleUrls: ['./docking-manage.component.css']
})
export class DockingManageComponent implements OnInit {
	tableData: any = []; // table的表单数据
	totalCounts: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	fileUp: string = '';
	fileToUpload: File = null; //上传文件回调参数
	activeSelected: string = ''; //row高亮
	// 查询参数
	selectedCompanyId: any = ""; // 选中的公司id
	selectedCompanyName: any = ""; // 选中的公司名称
	selectedDeviceId: any = ""; // 选中的设备ID
	selectedCarNumber: any = ""; // 选中的车牌号
	searchKey: any = ""; // 用户的搜索关键字
	sortTime: any = '2'; // 升降序的标志
	dateType: any = '1';
	dataSourceType: any = '';
	// 标志是否选择车辆的
	isShowDelete: any = false; //是否有删除权限
	specifyTime: {
		startTime: '',
		endTime: '',
	}
	startTime_search: string = '';
	endTime_search: string = '';
	specifyId = {
		picker1: 'datetimepicker3',
		picker2: 'datetimepicker4'
	}
	// 表单验证
	validatorOptions = {
		excluded: [':disabled'],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			payDate: {
				validators: {
					notEmpty: {
						message: '请选择缴费时间'
					}
				}
			},
			deviceIds: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请点击上方按钮选择车辆数据'
					}
				}
			},
			// renewalTime: {
			// 	validators: {
			// 		notEmpty: {
			// 			message: '请输入续费时长[月]'
			// 		}
			// 	}
			// }
			// projectIds: {
			// 	trigger: "change",
			// 	validators: {
			// 		notEmpty: {
			// 			message: '请点击上方按钮选择项目数据'
			// 		}
			// 	}
			// },
		}
	}
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
		});
	}
	ngOnInit() {
		this.initBtn();
		this.load();
		//树形图回车监听
		$("#searchKeyTree").bind("keydown", function (e) {
			var theEvent = e || window.event;
			var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
			if (code == 13) {
				this.list_search();
			}
		});
		let timer = setTimeout(() => {
			// 初始化树
			this.initProjectTree();
			clearTimeout(timer)
			timer = null;
		}, 1000);
	}
	// 初始化权限按钮
	//初始化权限按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_system:dockingManage')));
		if (!btnData) {
			return
		};
		for (let item of btnData) {
			if (item.sourceKey === "system:docking:deleteBtn" && item.parentId) {
				this.isShowDelete = true;
			}

		}
	}
	load() {
		let param = {
			"pageSize": this.pageSize,
			"nowPage": this.curPage,
			"parameters": {
				companyId: this.selectedCompanyId,
				deviceId: this.selectedDeviceId,
				carNumber: this.selectedCarNumber,
				searchKey: common.stringTrim(this.searchKey),
				startTime: this.startTime_search,
				endTime: this.endTime_search,
				sortTime: this.sortTime,
				dateType: this.dateType,
				export: '0',
				billType: '2',//账单类型（1.服务费，2.对接费）
				dataSourceType: this.dataSourceType
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("renewal/v2/list.html", reqdata).subscribe(result => {
			let data = []
			if (result.isSuccess && result.exhibitDatas) {
				data = result.exhibitDatas
				this.tableData = result.exhibitDatas
				this.totalCounts = result.recordCount;
			}
		});
	}
	changeDateType() {
		this.curPage = 1
		this.load()
	}
	//公司选中回调
	companySelected(data) {
		this.selectedDeviceId = data.deviceId;
		this.selectedCarNumber = data.carNumber;
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
	// 分页回调
	paginate(e) {
		this.activeSelected = '';
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	// 刷新表
	refresh() {
		this.curPage = 1
		this.load();
	}
	// 切换倒序升序
	columnSort(sort, type) {
		this.sortTime = sort.toString()
		this.dateType = type.toString()
		this.curPage = 1
		this.load()
	}
	// 删除续费记录
	del_domCode(row) {
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(() => {
			this.jsonApiService.http_get("renewal/v2/remove.html?id=" + row.id).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
			})
		})
	}
	// 表单查询
	tableSearch() {
		this.curPage = 1;
		this.load();
	}



	isUpload: any = ''; //是否是导入
	isScroTopNum: any = 0;  //当用户重新点开添加再进行点击车辆选择时才滚动到头部 其他时候不滚动
	// 添加续费记录的弹窗
	showAddRenewal(modal) {
		this.isScroTopNum = 0;
		modal.show();
		this.initRenewalDate()
		this.resetForm();
	}
	// 重置添加表
	resetForm() {
		// 重置车辆树
		$("#deviceList").jstree('uncheck_all');
		$('#searchKeyList').val("")
		$(".jstree-anchor").removeClass("jstree-clicked")
		$(".jstree-anchor").removeClass("jstree-search").removeClass("jstree-hovered")
		$("#searchCountWrap").css("display", "none")
		this.searchResult = 0;
		this.findIndex = 0;
		//重置项目树
		$("#deviceProjectList").jstree('uncheck_all');
		$('#searchProjectList').val("")
		$("#searchCountProject").css("display", "none")
		this.searchProjectResult = 0;
		this.findProjectIndex = 0;
		//初始化表单
		$("#addRenewal").data('bootstrapValidator').resetForm();
		this.selectedCar = [];
		this.renewalData = [];
		$("#deviceIds").val("")

		this.selectedProject = [];
		this.renewalProjectData = [];
		$("#projectIds").val("")

		this.renewal = {
			renewalData: [],
			payDate: common.getNowTime(),      //缴费时间
			renewalTime: "", // 续费时长
			remark: "", //备注 
			billType: '2',//账单类型（1.服务费，2.对接费）
		}
	}
	// 关闭添加弹框
	closeRenewalModal(modal) {
		$("#addRenewal").data('bootstrapValidator').resetForm();
		modal.hide();
	}
	// 提交添加结果
	submitModal(modal1, modal2, type) {
		if (this.renewalData.length > 800) {
			this.jsonApiService.message("数据量太大，请缩减下再次请求");
			return
		}
		$('#addRenewal').bootstrapValidator('validate'); //开启验证
		let isValid = $('#addRenewal').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			this.renewal.renewalData = JSON.stringify(this.renewalData)
			var url = '?payDate=' + this.renewal.payDate + '&renewalTime=' + this.renewal.renewalTime + '&remark=' + this.renewal.remark + '&billType=' + this.renewal.billType + '&dataSource=' + this.renewal.dataSource
			this.jsonApiService.json_http("renewalTemp/uploadTempRecords.html" + url, this.renewal.renewalData).subscribe(data => {
				if (data.success) {
					this.closeRenewalModal(modal1)
					this.showSubmitCheck(modal2, data.data)
					this.isUpload = type
					this.isShowUpload = false;
				}
			})
		}
	}
	//时间change回调
	datePickerSelected(val) {
		this.renewal.payDate = val.endTime;
	}


	// 显示车辆选择弹窗
	showCarTree(modal) {
		if (this.renewalProjectData.length == 0) {
			layer.msg('请先选择项目', {
				icon: 0
			});
			return
		}
		// 先清空再勾选
		$("#deviceList").jstree('uncheck_all');
		for (let i = 0; i < this.selectedCar.length; i++) {
			$('#deviceList').jstree().select_node("#" + this.selectedCar[i].id)
		}
		modal.show();

		// 当用户点击完添加第一次点开车辆树时会滚动到头部
		this.isScroTopNum++;
		if (this.isScroTopNum <= 1 || this.selectedCar.length == 0) {
			let timer = setTimeout(() => {
				$('#tree_content').scrollTop(0);
				clearTimeout(timer)
				timer = null
			}, 200);
		}
	}
	// 关闭车辆选择弹框
	closeCarTreeModal(modal) {
		modal.hide();
	}
	// 选择车辆树的弹框提交
	selectCarSubmit(modal) {
		modal.hide();
		this.userDevicePermissionSubmit();
	}
	// 删除选择的车辆
	deleteSelectCar(id, index) {
		/**
		 * 1、删除传递给后端的数据
		 * 2、在树中选中的列表中删除选中  jstree.unselect
		 * 3、再展示的数组中删除该数据
		 * */
		var selectConmanyId;
		$('#deviceList').jstree(true).deselect_node("#" + id);
		this.selectedCar.splice(index, 1)
		for (let i = 0; i < this.renewalData.length; i++) {
			if (this.renewalData[i].id == id) {
				selectConmanyId = this.renewalData[i].companyId
				this.renewalData.splice(i, 1)
			}
		}
		if (this.renewalData.length == 0) {
			$("#deviceIds").val("").trigger("change")
		}
		var flag = true //默认不存在
		//判断是否全部删除已选项目的车辆
		var selectProjectId = this.findCompany(selectConmanyId, this.jsTreeData)
		for (let j = 0; j < this.renewalData.length; j++) {
			var selectCompanyId = this.findCompany(this.renewalData[j].companyId, this.jsTreeData)
			if (selectCompanyId == selectProjectId) {
				flag = false
			}
		}
		if (flag) {
			for (let k = 0; k < this.renewalProjectData.length; k++) {
				if (this.renewalProjectData[k] == selectProjectId) {
					this.renewalProjectData.splice(k, 1)
					$('#deviceProjectList').jstree(true).deselect_node("#" + this.renewalProjectData[k]);
					this.selectedProject.splice(k, 1)
				}
			}
			if (this.renewalProjectData.length == 0) {
				$("#projectIds").val("").trigger("change")
			}
		}
	}

	jsTreeData: any = []; //所有车辆数据
	selectedCar: any = []; // 选择的车辆
	renewalData: any = []; // 组装的数据
	// 添加时传递给后端的对象
	renewal: any = {
		renewalData: [],
		payDate: "",
		renewalTime: "",
		remark: "", //备注
		billType: '2',//账单类型（1.服务费，2.对接费）
	}
	// 初始化车辆数据
	initDeviceTree(dataList) {
		var _that = this;
		$('#deviceList').jstree({
			"core": {
				'data': function (obj, callback) {
					var jsonstr = "[]";
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'renewal/getCarTreeByCompanyIds.html';
					$.ajax({
						type: "POST",
						url: config.BaseURL + url,
						dataType: "json",
						cache: false,
						data: {
							companyIds: dataList
						},
						xhrFields: {
							withCredentials: true
						},
						success: function (data: any) {
							var result = data.data;
							jsonarray = result;
							_that.jsTreeData = result.filter((obj) => { return obj.remark == 'company' })
							callback.call(this, jsonarray);
						}.bind(this)
					});
				}.bind(this),
				"themes": {
					"responsive": true
				},
				"multiple": true,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"checkbox": {
				"keep_selected_style": false,
				"three_state": true, //父子级别级联选择
				"cascade": "down"
			},
			"plugins": ["checkbox", "search"]
		})

	}
	// 总共搜索到的数据
	searchResult = 0;
	// 第几个
	findIndex = 0;
	// 车辆数的搜索
	list_search() {
		let that = this;
		let searchkey = ($('#searchKeyList').val() + "").trim();
		if (!searchkey) {
			$("#searchCountWrap").css("display", "none")
			return;
		}
		$("#deviceList").jstree(true).search(searchkey);
		this.searchResult = $('#deviceList .jstree-search').length;
		if (this.searchResult < 1) {
			$("#searchCountWrap").css("display", "none")
			layer.msg('没有对应数据', {
				icon: 0
			});
			return;
		}
		// 这里是进行搜索的地方
		$('#deviceList .jstree-search').each(function (index, obj) {
			if (index < 1) {//js树搜索定位到结果的第一个地方；
				$("#searchCountWrap").css("display", "inline-block")
				that.findIndex = 0;
				$("#findIndex").text(that.findIndex + 1)
				$("#searchResult").text(that.searchResult)
				// 滚动
				var container = $('#tree_content'),
					scrollTo = $(this);
				$(this).addClass("jstree-hovered")
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());
				container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#tree_content').height() * 0.3 });
			}
		})
	}
	// 向前寻找
	preFind() {
		let that = this;
		if (this.findIndex <= 0 && this.searchResult != 0) {
			this.findIndex = 0;
			this.jsonApiService.message('已是第一条数据');
		} else {
			this.findIndex--;
			$("#findIndex").text(this.findIndex + 1)
			$('#deviceList .jstree-search').each(function (index, obj) {
				$(this).removeClass("jstree-hovered")
				if (index == that.findIndex) {
					var container = $('#tree_content'),
						scrollTo = $(this);
					// container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());
					$(this).addClass("jstree-hovered")
					container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - 100 });
				}
			})
		}

	}
	// 向后寻找
	nextFind() {
		let that = this;
		if (this.searchResult != 0 && this.searchResult <= (this.findIndex + 1)) {
			this.findIndex = this.searchResult - 1
			this.jsonApiService.message('已是最后一条数据');
		} else {
			this.findIndex++;
			$("#findIndex").text(this.findIndex + 1)
			$('#deviceList .jstree-search').each(function (index, obj) {
				$(this).removeClass("jstree-hovered")
				if (index == that.findIndex) {
					var container = $('#tree_content'),
						scrollTo = $(this);
					$(this).addClass("jstree-hovered")
					// container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());
					container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - 100 });
				}
			})
		}
	}
	// 选择车辆树的提交
	userDevicePermissionSubmit() {
		var tree = $('#deviceList').jstree();
		var selected = tree.get_checked(true);   //获取所有选中节点
		this.renewalData = []; // 传递给后台的数据
		this.selectedCar = [];

		var len = selected.length;  //选择的车的设备id  还有他的车牌号
		let count = 0;
		for (var i = 0; i < len; i++) {
			if (selected[i].original.remark === 'car') {
				count++;
				if (count == 1) {
					// 获取第一个车辆的对接公司的周期
					this.getCompanyCycle(selected[i].original.parent)
				}
				this.selectedCar.push(selected[i].original);
				// 组装renewalData
				this.renewalData.push({ companyId: selected[i].original.parent, id: selected[i].original.id })
			}
		}
		// this.selectedCar = [];
		// 展示的车牌号数据
		let timer = setTimeout(() => {
			if (this.selectedCar.length == 0) {
				$("#deviceIds").val("").trigger("change")
			} else {
				$("#deviceIds").val(this.selectedCar[0].text).trigger("change")
			}
			$("#addRenewal").data('bootstrapValidator').resetForm()
			clearTimeout(timer)
			timer = null;
		}, 200);
	}
	// 根据公司id获取公司的周期
	getCompanyCycle(id) {
		let reqdata = 'companyId=' + id;
		this.jsonApiService.http("renewal/getCompanyInfo.html", reqdata).subscribe(data => {
			if (data.success) {
				this.renewal.renewalTime = data.data.renewalCycle
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}

	//递归查找父级公司
	findCompany(id, list) {
		var jsTreeId = '', jsTreeDataList = [], returnId;
		var listData = JSON.parse(JSON.stringify(list))
		for (let i = 0; i < listData.length; i++) {
			if (listData[i].id == id) {
				if (listData[i].parent == '#') {
					returnId = id
					break;
				} else {
					jsTreeId = list[i].parent;
					listData.splice(i, 1)
					jsTreeDataList = JSON.parse(JSON.stringify(listData))
					this.findCompany(jsTreeId, jsTreeDataList)
					returnId = jsTreeId
					break
				}
			}
		}
		return returnId
	}


	// 显示导入弹框
	showImportModal(modal) {
		// 清空选择的文件
		modal.show();
		this.fileToUpload = null;
	}
	// 关闭导入弹窗
	cancelUp(modal) {
		modal.hide();
		this.fileToUpload = null;
	}
	// 下载模板
	load_module() {
		var elemIF = document.createElement("iframe");
		elemIF.src = config.BaseURL + 'resources/template/renewal-Template.xlsx';
		elemIF.style.display = "none";
		document.body.appendChild(elemIF);
	}
	// 清空input type=file输入框的值
	clearFile() {
		this.fileUp = '';
	}
	//文件上传change回调
	fileChange(files: FileList) {
		this.fileToUpload = files.item(0);
		const isEXCEL = this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || this.fileToUpload.type === "application/vnd.ms-excel";
		if (!isEXCEL) {
			this.jsonApiService.message('上传文件只能是 excel格式!');
			this.fileToUpload = null;
			return;
		}
	}
	//导入submit
	submitData(modal1, modal2, type) {
		let postParam = new FormData();
		postParam.append('file', this.fileToUpload);
		postParam.append('billType', '2'); //账单类型（1.服务费，2.对接费）
		if (!this.fileToUpload) {
			this.jsonApiService.message('请上传文件')
			return false;
		}
		this.jsonApiService.form_http("renewalTemp/importExcelData.html", postParam).subscribe(data => {
			if (data.success) {
				modal1.hide();
				this.fileToUpload = null;
				this.isShowUpload = true;
				this.showSubmitCheck(modal2, data.data)
				this.isUpload = type
			}
		})
	}
	// 数据导出
	exportData() {
		var params = {
			"pageSize": this.pageSize,
			"nowPage": this.curPage,
			"parameters": {
				companyId: this.selectedCompanyId,
				deviceId: this.selectedDeviceId,
				carNumber: this.selectedCarNumber,
				searchKey: common.stringTrim(this.searchKey),
				startTime: this.startTime_search,
				endTime: this.endTime_search,
				sortTime: this.sortTime,
				dateType: this.dateType,
				export: '1',
				billType: '2',//账单类型（1.服务费，2.对接费）
				dataSourceType: this.dataSourceType
			}
		};
		let timeCheck = common.correctTime(params.parameters, ['export', 'dateType', 'sortTime'])
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(params, 'gridPager', config.BaseURL + 'renewal/v2/list.html')
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time) {
		this.startTime_search = time.startTime;
		this.endTime_search = time.endTime;
	}

	// 数据清洗弹窗
	dataCleaningForm: any = {
		startTime: '',
		endTime: '',
		companyName: '',
		companyId: '',
		dataCleanout: '',
		billType: '2',//账单类型（1.服务费，2.对接费）
	}
	// 表单验证
	cleaningOptions = {
		excluded: [':disabled'],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			companyName: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择厂区'
					}
				}
			},
			startInstallTime: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择开始时间'
					}
				}
			},
			installTime: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择结束时间'
					}
				}
			},
			dataCleanout: {
				validators: {
					notEmpty: {
						message: '请输入保留条数'
					}
				}
			}
		}
	}
	dataCleaning(modal) {
		this.initDate();
		$("#dataCleaning").data('bootstrapValidator').resetForm();
		this.eliminateForm();
		modal.show();
	}
	// 关闭添加弹框
	closeCleaningModal(modal) {
		$("#dataCleaning").data('bootstrapValidator').resetForm();
		this.eliminateForm();
		modal.hide();
	}
	eliminateForm() {
		$('#startInstallTime').val('');
		$('#installTime').val('');
		Object.keys(this.dataCleaningForm).map(item => this.dataCleaningForm[item] = '')
	}
	// 提交数据清洗
	submitCleaningModal(modal) {
		$('#dataCleaning').bootstrapValidator('validate'); //开启验证
		let isValid = $('#dataCleaning').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			this.dataCleaningForm.startTime = $('#startInstallTime').val();
			this.dataCleaningForm.endTime = $('#installTime').val();
			this.jsonApiService.http("renewal/v2/getDataCleanout.html", this.joinParams(this.dataCleaningForm)).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					this.eliminateForm();
					this.closeRenewalModal(modal)
				}
			})
		}
	}
	joinParams(parmas) {
		return Object.keys(parmas).map(key => key + '=' + parmas[key]).join('&')
	}
	//初始化日期
	initDate() {
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					common.initDatePicker("#auditorTime", 0);
					$("#startInstallTime").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						if (!date) { return; }
						var time = common.getTimeMmss(date);
						$("#installTime").datetimepicker("setStartDate", time);
					});
					$("#installTime").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						if (!date) { return; }
						var time = common.getTimeMmss(date);
						$("#startInstallTime").datetimepicker("setEndDate", time);
					});
				});
			});
	}

	//初始化日期
	initRenewalDate() {
		var that = this;
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#payDate").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
						endDate: common.getNowTime()
					}).on("changeDate", function (e) {
						var date = e.date;
						if (!date) { return; }
						var time = common.getTimeMmss(date);
						// $("#payDate").datetimepicker("setEndDate", time);
						that.renewal.payDate = time
					});
				});
			});
	}
	//新增或者编辑公司选中回调
	addCompanySelected(data) {
		this.dataCleaningForm.companyId = data.companyId || '';
		this.dataCleaningForm.companyName = data.companyName;
	}




	/**
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 项目弹框
	 * 
	 * 
	 * 
	 * 
	 * 
	 * 
	 */
	// 显示项目选择弹窗
	showProject(modal) {
		// 先清空再勾选
		$("#deviceProjectList").jstree('uncheck_all');
		for (let i = 0; i < this.selectedProject.length; i++) {
			$('#deviceProjectList').jstree().select_node("#" + this.selectedProject[i].id)
		}
		modal.show();

		// 当用户点击完添加第一次点开项目时会滚动到头部
		this.isScroTopNum++;
		if (this.isScroTopNum <= 1 || this.selectedProject.length == 0) {
			let timer = setTimeout(() => {
				$('#tree_project_content').scrollTop(0);
				clearTimeout(timer)
				timer = null
			}, 200);
		}
	}
	// 关闭项目选择弹框
	closeProjectModal(modal) {
		modal.hide();
	}
	// 选择项目树的弹框提交
	selectProjectSubmit(modal) {
		modal.hide();
		this.userDeviceProjectSubmit();
	}
	// 删除选择的项目
	deleteSelectProject(id, index) {
		/**
		 * 1、删除传递给后端的数据
		 * 2、在树中选中的列表中删除选中  jstree.unselect
		 * 3、再展示的数组中删除该数据
		 * */
		$('#deviceProjectList').jstree(true).deselect_node("#" + id);
		this.selectedProject.splice(index, 1)
		for (let i = 0; i < this.renewalProjectData.length; i++) {
			if (this.renewalProjectData[i] == id) {
				this.renewalProjectData.splice(i, 1)
			}
		}
		if (this.renewalProjectData.length == 0) {
			$("#projectIds").val("").trigger("change")
		}
		//判断已选车辆里面是不是有已选的项目
		if (this.renewalData.length > 0) {
			let arr = JSON.parse(JSON.stringify(this.renewalData))
			var K = arr.length;
			while (K--) {
				var companyId = this.findCompany(arr[K].companyId, this.jsTreeData)
				if (companyId) {
					if (companyId == id) {
						arr.splice(K, 1)
						// this.renewalData.splice(K, 1)
						this.selectedCar.splice(K, 1)
						$('#deviceList').jstree(true).deselect_node("#" + this.renewalData[K].id);
					}
				}
			}
			this.renewalData = JSON.parse(JSON.stringify(arr))
			if (this.renewalData.length == 0) {
				$("#deviceIds").val("").trigger("change")
			}
		}
		this.userDeviceProjectSubmit()
	}

	selectedProject: any = []; // 选择的项目
	renewalProjectData: any = []; // 组装的数据
	// 初始化项目数据
	initProjectTree() {
		var _that = this;
		$('#deviceProjectList').jstree({
			"core": {
				'data': function (obj, callback) {
					var jsonstr = "[]";
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/queryCompanyList.html';
					$.ajax({
						type: "POST",
						url: config.BaseURL + url,
						dataType: "json",
						data: {
							isStreamline: true
						},
						cache: false,
						xhrFields: {
							withCredentials: true
						},
						success: function (data) {
							var result = data.data;
							jsonarray = result;
							callback.call(this, jsonarray);
						}.bind(this)
					});
				}.bind(this),
				"themes": {
					"responsive": true
				},
				"multiple": true,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"checkbox": {
				"keep_selected_style": false,
				"three_state": true, //父子级别级联选择
				"cascade": "down"
			},
			"plugins": ["checkbox", "search"]
		})

	}
	// 总共搜索到的数据
	searchProjectResult = 0;
	// 第几个
	findProjectIndex = 0;
	// 项目的搜索
	list_project_search() {
		let that = this;
		let searchkey = ($('#searchProjectList').val() + "").trim();
		if (!searchkey) {
			$("#searchCountProject").css("display", "none")
			return;
		}
		$("#deviceProjectList").jstree(true).search(searchkey);
		this.searchProjectResult = $('#deviceProjectList .jstree-search').length;
		if (this.searchProjectResult < 1) {
			$("#searchCountProject").css("display", "none")
			layer.msg('没有对应数据', {
				icon: 0
			});
			return;
		}
		// 这里是进行搜索的地方
		$('#deviceProjectList .jstree-search').each(function (index, obj) {
			if (index < 1) {//js树搜索定位到结果的第一个地方；
				$("#searchCountProject").css("display", "inline-block")
				that.findProjectIndex = 0;
				$("#findProjectIndex").text(that.findProjectIndex + 1)
				$("#searchProjectResult").text(that.searchProjectResult)
				// 滚动
				var container = $('#tree_project_content'),
					scrollTo = $(this);
				$(this).addClass("jstree-hovered")
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());
				container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#tree_project_content').height() * 0.3 });
			}
		})
	}
	// 向前寻找
	preProjectFind() {
		let that = this;
		if (this.findProjectIndex <= 0 && this.searchProjectResult != 0) {
			this.findProjectIndex = 0;
			this.jsonApiService.message('已是第一条数据');
		} else {
			this.findProjectIndex--;
			$("#findProjectIndex").text(this.findProjectIndex + 1)
			$('#deviceProjectList .jstree-search').each(function (index, obj) {
				$(this).removeClass("jstree-hovered")
				if (index == that.findProjectIndex) {
					var container = $('#tree_project_content'),
						scrollTo = $(this);
					// container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());
					$(this).addClass("jstree-hovered")
					container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - 100 });
				}
			})
		}

	}
	// 向后寻找
	nextProjectFind() {
		let that = this;
		if (this.searchProjectResult != 0 && this.searchProjectResult <= (this.findProjectIndex + 1)) {
			this.findProjectIndex = this.searchProjectResult - 1
			this.jsonApiService.message('已是最后一条数据');
		} else {
			this.findProjectIndex++;
			$("#findProjectIndex").text(this.findProjectIndex + 1)
			$('#deviceProjectList .jstree-search').each(function (index, obj) {
				$(this).removeClass("jstree-hovered")
				if (index == that.findProjectIndex) {
					var container = $('#tree_project_content'),
						scrollTo = $(this);
					$(this).addClass("jstree-hovered")
					// container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());
					container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - 100 });
				}
			})
		}
	}
	// 选择项目的提交
	userDeviceProjectSubmit() {
		var tree = $('#deviceProjectList').jstree();
		var selected = tree.get_checked(true);   //获取所有选中节点
		this.renewalProjectData = []; // 传递给后台的数据

		var len = selected.length, selectedCarNumbers = [];  //选择的车的设备id  还有他的车牌号
		let count = 0;
		for (var i = 0; i < len; i++) {
			count++;
			if (count == 1) {
				// 获取第一个项目的对接公司的周期
				this.getCompanyProject(selected[i].original.id)
			}
			selectedCarNumbers.push(selected[i].original);
			// 组装renewalData
			this.renewalProjectData.push(selected[i].original.id)

		}
		this.selectedProject = [];
		// 展示的项目名称数据
		this.selectedProject = selectedCarNumbers
		let timer = setTimeout(() => {
			if (this.selectedProject.length == 0) {
				$("#projectIds").val("").trigger("change")
			} else {
				$('#deviceList').jstree("destroy");
				this.initDeviceTree(this.renewalProjectData.join(','));
				$("#projectIds").val(this.selectedProject[0].text).trigger("change")
			}

			clearTimeout(timer)
			timer = null;
		}, 200);
	}
	// 根据公司id获取公司的周期
	getCompanyProject(id) {
		let reqdata = 'companyId=' + id;
		this.jsonApiService.http("renewal/getCompanyInfo.html", reqdata).subscribe(data => {
			if (data.success) {
				this.renewal.renewalTime = data.data.renewalCycle
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}


	/**
	 * 提交核对
	 */
	submitCheckTableData: any = []; //核对列表
	isSuccess: string = ''//提交前状态
	projectVersion: string = '';
	isShowUpload: boolean = false // 是否是导入的弹框
	//显示
	showSubmitCheck(modal, version) {
		this.projectVersion = version;
		this.check_table_search(modal)

	}
	//关闭
	cancelSubmitCheck(modal2, modal1) {
		this.isSuccess = "";
		this.submitCheckTableData = [];
		this.projectVersion = ''
		modal2.hide();
		if (!this.isShowUpload) modal1.show()
	}
	queryCheckTable() {
		this.checkPageSize = 10
		this.checkCurPage = 1
		this.check_table_search('')
	}
	//查询
	check_table_search(modal) {
		let param = {
			"pageSize": this.checkPageSize,
			"nowPage": this.checkCurPage,
			"parameters": {
				version: this.projectVersion,
				isSuccess: this.isSuccess
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("renewalTemp/pageList.html", reqdata).subscribe(result => {
			if (result.success) {
				this.submitCheckTableData = result.data.exhibitDatas
				if (modal) modal.show()
				for (let item of this.submitCheckTableData) {
					item['isChecked'] = false;
				}
				this.allChecked = false
				this.selected = []
				this.numMessage = result.message
				this.rowId = ''
				this.checkTotalCounts = result.data.recordCount;
			} else {
				this.numMessage = ''
			}
		});
	}
	//提交
	submitCheck(modal) {
		let isSubmit = true;
		if (this.submitCheckTableData.length == 0) {
			this.jsonApiService.message('暂无需要提交核对的数据');
			return
		}

		for (let i = 0; i < this.submitCheckTableData.length; i++) {
			if (this.submitCheckTableData[i].isSuccess == 0) {
				isSubmit = false
				this.jsonApiService.message('列表中存在失败状态的数据');
				return
			}
		}

		if (isSubmit) {
			this.jsonApiService.http_obj("renewalTemp/submit.html", { version: this.projectVersion }).subscribe(result => {
				this.jsonApiService.message(result.message);
				if (result.success) {
					this.isSuccess = "";
					this.submitCheckTableData = [];
					this.projectVersion = ''
					this.resetForm()
					modal.hide()
					this.load();
				}
			});
		}

	}
	//删除
	delSubmitCheck(row) {
		this.jsonApiService.confirm_message('此操作将删除临时数据,确认要删除').then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("renewalTemp/deleteRenewalTemp.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.check_table_search('');
				}
			})
		})
	}
	editcheckForm: any = {
		billType: '2',
		carNumber: "",
		companyId: "",
		companyName: "",
		renewalDate: "",
		createUser: "",
		dataSource: '3',
		deviceId: "",
		// endTime: "",
		errorMsg: "",
		firstServiceEndDate: "",
		id: "",
		isSuccess: '',
		projectId: "",
		remark: "",
		renewalCycle: '',
		startTime: "",
		version: ''
	}
	DockingList: any = []
	//编辑
	editSubmitCheck(row, modal) {
		// let reqdata = 'id=' + row.id;
		//获取编辑详情
		this.jsonApiService.http_get("renewalTemp/findRecordById.html?id=" + row.id).subscribe(data => {
			if (data.success) {
				this.DockingList = data.data.companys
				this.editcheckForm = data.data.record
				modal.show()
				// delete this.editcheckForm.changeDate
				this.initCreateDate()
			}
		})
	}
	//初始化日期
	initCreateDate() {
		var that = this;
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#renewalDate").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
						endDate: new Date()
					}).on("changeDate", function (e) {
						var date = e.date;
						if (!date) { return; }
						var time = common.getTimeMmss(date);
						// $("#createDate").datetimepicker("setStartDate", time);
						that.editcheckForm.renewalDate = time
						// that.countPay()
					});
				});
			});
	}
	dockingListChange() {
		for (let item of this.DockingList) {
			if (item.value === this.editcheckForm.companyId) {
				this.editcheckForm.companyName = item.companyName;
				this.editcheckForm.firstServiceEndDate = item.firstTime
				this.editcheckForm.deviceId = item.deviceId
				this.editcheckForm.projectId = item.projectId
				// this.countPay()
			}
		}
	}
	//关闭编辑
	closeEditSubmitCheck(modal) {
		modal.hide()
	}
	//提交编辑
	submitEditSubmitCheck(modal) {
		if (!this.editcheckForm.renewalDate) {
			this.jsonApiService.message('缴费时间不能为空');
			return
		}
		if (!this.editcheckForm.renewalCycle) {
			this.jsonApiService.message('续费时长不能为空');
			return
		}
		this.jsonApiService.json_http("renewalTemp/updateRenewalTemp.html", this.editcheckForm).subscribe(result => {
			this.jsonApiService.message(result.message);
			if (result.success) {
				modal.hide()
				this.check_table_search('');
			}
		});
	}
	renewalCycleChange() {
		// this.countPay(); //计算
	}
	//计算续费
	countPay() {
		//续费时长=12，则直接在原到期时间上，增加一年
		if (this.editcheckForm.renewalCycle == 12) {
			let date1 = parseInt(this.editcheckForm.firstServiceEndDate.substring(0, 4)) + 1
			let date2 = this.editcheckForm.firstServiceEndDate.substring(4, this.editcheckForm.firstServiceEndDate.length)
			this.editcheckForm.endTime = date1 + date2
		} else {
			if (this.editcheckForm.renewalCycle) {
				var str2 = this.editcheckForm.renewalDate.substr(10, this.editcheckForm.renewalDate.length - 1)
				var str1 = this.editcheckForm.renewalDate.replace(/-/g, '/'); //'2018/01/01 00:00:00'
				var date = new Date(Date.parse(str1)); //date格式的时间类型
				var nowDate = this.addMonth(date, this.editcheckForm.renewalCycle); //date格式的时间类型
				this.editcheckForm.endTime = this.format(nowDate) + str2
			}
		}
	}

	addMonth(date, addMonth) {
		var y = date.getFullYear();
		var m = date.getMonth();
		var nextY = y;
		var nextM = m;
		//如果当前月+要加上的月>11 这里之所以用11是因为 js的月份从0开始
		if ((m + parseInt(addMonth)) > 11) {
			nextY = y + 1;
			nextM = m + parseInt(addMonth) - 12;
		} else {
			nextM = date.getMonth() + parseInt(addMonth)
		}
		var daysInNextMonth = this.daysInMonth(nextY, nextM);
		var day = date.getDate();
		if (day > daysInNextMonth) {
			day = daysInNextMonth;
		}
		return new Date(nextY, nextM, day);
	}
	daysInMonth(year, month) {
		if (month == 1) {
			if (year % 4 == 0 && year % 100 != 0)
				return 29;
			else
				return 28;
		} else if ((month <= 6 && month % 2 == 0) || (month = 6 && month % 2 == 1))
			return 31;
		else
			return 30;
	}
	format(nowDate) {
		var format = 'yyyy-MM-dd'
		var date = {
			"M+": nowDate.getMonth() + 1,
			"d+": nowDate.getDate(),
			"h+": nowDate.getHours(),
			"m+": nowDate.getMinutes(),
			"s+": nowDate.getSeconds(),
			"q+": Math.floor((nowDate.getMonth() + 3) / 3),
			"S+": nowDate.getMilliseconds()
		};
		if (/(y+)/i.test(format)) {
			format = format.replace(RegExp.$1, (nowDate.getFullYear() + '').substr(4 - RegExp.$1.length));
		}
		for (var k in date) {
			if (new RegExp("(" + k + ")").test(format)) {
				format = format.replace(RegExp.$1, RegExp.$1.length == 1
					? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
			}
		}
		return format;
	};
	numMessage: any = ''; //显示数量
	// 核对数据的导出
	exportCheckData() {
		var params = {
			version: this.projectVersion,
			isSuccess: this.isSuccess,
			ids: this.rowId
		};
		common.exprotDataFile(params, 'gridPager', config.BaseURL + 'renewalTemp/exportRenewalTempData.html')
	}
	//批量删除
	allChecked: boolean = false;//table全选状态值
	selected: any[] = []; //row选择的数据
	rowId: string = ''; //批量
	//table 全部选中
	allSelected() {
		this.allChecked = !this.allChecked;
		if (!this.allChecked) {
			for (let item of this.submitCheckTableData) {
				item['isChecked'] = false;
			}
			this.selected = [];
			this.rowId = '';
		} else {
			var temArr = [];
			for (let item of this.submitCheckTableData) {
				item['isChecked'] = true;
				temArr.push(item.id);
				this.selected.push(item);
			}
			for (let item of this.selected) {
				temArr.push(item.rowId);
			}
			this.rowId = temArr.join(',');
		}
	}
	//table复选框数据row选中事件回调:处理选中状态和deviceId
	rowSelected(row, e, index) {
		var index = $.inArray(row, this.selected);
		if (index === -1) {
			row.isChecked = true;
			this.selected.push(row);
		} else {
			row.isChecked = false;
			this.selected.splice(index, 1);
		}
		var temArr = [];
		for (let item of this.selected) {
			temArr.push(item.id);
		}
		this.rowId = temArr.join(','); //处理deviceId,与后台接口交互参数
		this.selected.length === this.submitCheckTableData.length ? this.allChecked = true : this.allChecked = false; //判断是否全选状态
	}
	batchDelete() {
		console.log(this.selected, this.rowId)
		if (this.selected.length && this.rowId != '') {
			this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
				let reqdata = 'id=' + this.rowId;
				this.jsonApiService.http("renewalTemp/deleteRenewalTemp.html", reqdata).subscribe(data => {
					this.jsonApiService.message(data.message);
					this.check_table_search('');
				})
			})
		} else {
			this.jsonApiService.message('请选中最少一条数据');
		}

	}

	checkCurPage: number = 1;
	checkPageSize: number = 10;
	checkTotalCounts: number = 0; //分页总条数
	// 分页回调
	checkPaginate(e) {
		this.checkCurPage = e.page + 1;
		this.checkPageSize = e.rows;
		this.check_table_search('');
	}
	// 刷新表
	checkRefresh() {
		this.check_table_search('');
	}



	/**
	 * 编辑数据来源
	 */
	dataSource: any = '';
	dataRowId: any = '';
	editSource(row, modal) {
		if (row.dataSource == 1 || row.dataSource == '' || row.dataSource == null) {
			this.dataSource = 1
		} else {
			this.dataSource = row.dataSource
		}
		this.dataRowId = row.id
		modal.show()
	}
	//关闭
	closeEditSourceModal(modal) {
		this.dataRowId = ''
		modal.hide()
	}
	//提交
	submitEditSourceModal(modal) {
		this.jsonApiService.http_obj("renewal/v2/updateRenewalRecord.html", { dataSource: this.dataSource, id: this.dataRowId }).subscribe(result => {
			this.jsonApiService.message(result.message);
			if (result.success) {
				modal.hide()
				this.dataSource = ''
				this.dataRowId = ''
				this.load();
			}
		});
	}
}